from flask import Blueprint, render_template, request
from applications.common.utils.rights import authorize
from flask_login import login_required
from applications.common.utils.validate import xss_escape
from applications.common.utils.http import table_api, success_api, fail_api
from applications.common.helper import ModelFilter
from applications.common.curd import model_to_dicts, enable_status, disable_status, get_one_by_id
from applications.models import UrlModel,CategoryModel
from applications.schemas import MsgUrlOutSchema
from applications.extensions import db

spider_msg = Blueprint('spiderMsg', __name__, url_prefix='/spider/msg')


@spider_msg.get('/')
@authorize("spider:msg:main", log=True)
def main():
    return render_template('spider/msg/main.html')


@spider_msg.get('/data')
@authorize("spider:msg:main", log=True)
def table():
    msg_title = xss_escape(request.args.get("msgTitle", type=str))
    msg_url = xss_escape(request.args.get("msgUrl", type=str))
    mf = ModelFilter()
    if msg_title:
        mf.vague(field_name="title", value=msg_title)
    if msg_url:
        mf.vague(field_name="href", value=msg_url)

    msg = UrlModel.query.filter(mf.get_filter(UrlModel)).layui_paginate()
    count = msg.total
    return table_api(data=model_to_dicts(schema=MsgUrlOutSchema, data=msg.items), count=count)


@spider_msg.get('/add')
@authorize("spider:msg:add", log=True)
def add():
    categorys=CategoryModel.query.all()
    return render_template('spider/msg/add.html',categorys=categorys)


@spider_msg.post('/save')
@authorize("spider:msg:add", log=True)
def save():
    req = request.json
    details = xss_escape(req.get("details"))
    enable = xss_escape(req.get("enable"))
    msgTitle = xss_escape(req.get("msgTitle"))
    msgUrl = xss_escape(req.get("msgUrl"))
    category_id=xss_escape(req.get("categoryIds"))
    msg = UrlModel(
        details=details,
        enable=enable,
        title=msgTitle,
        href=msgUrl,
        category_id=category_id
    )
    db.session.add(msg)
    db.session.commit()
    return success_api(msg="成功")


@spider_msg.put('/enable')
@authorize("spider:msg:edit", log=True)
def enable():
    id = request.json.get('msgId')
    if id:
        res = enable_status(UrlModel, id)
        if not res:
            return fail_api(msg="出错了")
        return success_api(msg="启动成功")
    return fail_api("数据错误")


@spider_msg.put('/disable')
@authorize("spider:msg:edit", log=True)
def dis_enable():
    _id = request.json.get('msgId')
    if _id:
        res = disable_status(UrlModel, _id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="禁用成功")
    return fail_api(msg="数据错误")


@spider_msg.get('/edit/<int:id>')
@authorize("spider:msg:edit", log=True)
def edit(id):
    m = get_one_by_id(model=UrlModel, id=id)
    categorys=CategoryModel.query.all()
    return render_template('spider/msg/edit.html',messagge=m,categorys=categorys)


@spider_msg.put('/update')
@authorize("spider:msg:edit", log=True)
def update():
    req_json = request.json
    id = req_json.get("msgId")
    data = {
        "href": xss_escape(req_json.get("msgUrl")),
        "title": xss_escape(req_json.get("msgTitle")),
        "enable": xss_escape(req_json.get("enable")),
        "details": xss_escape(req_json.get("details")),
        "time":xss_escape(req_json.get("msgTime")),
        "category_id":xss_escape(req_json.get("categoryIds"))
    }
    msg = UrlModel.query.filter_by(id=id).update(data)
    db.session.commit()
    if not msg:
        return fail_api(msg="更新失败")
    return success_api(msg="更新成功")


@spider_msg.delete('/remove/<int:id>')
@authorize("spider:msg:remove", log=True)
def remove(id):
    m = UrlModel.query.filter_by(id=id).delete()
    db.session.commit()
    if not m:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


@spider_msg.delete('/batchRemove')
@authorize("spider:msg:remove", log=True)
def batch_remove():
    ids = request.form.getlist("ids[]")
    for id in ids:
        m = UrlModel.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")
